const express = require('express');
const fs = require('fs');
const path = require('path');
const SqliteDB = require('../../config/sqlite');

const reportRouter = express.Router();
const db = new SqliteDB();

reportRouter.post('/getTimeoutReportList', (req, res) => {
    const { courseName, className } = req.body;
    db.executeQuery(`select * from zip_progress where course_name = ? and class_name = ?`, [courseName, className], rows => {
        res.json({
            status: 200,
            message: '操作成功',
            data: rows
        });
    });
});

reportRouter.post('/downloadReportZip', async (req, res) => {
    // 读取压缩包
    const { id, created_at, class_name, course_name } = req.body;
    const filePath = path.join(__dirname, `../../pdfZip/${created_at.slice(0, 10)}/${id}.zip`);
    fs.readFile(filePath, (err, data) => {
        if (err) {
            res.json({
                status: 500,
                message: '文件不存在'
            });
        } else {
            const reportName = encodeURI(course_name + ' ' + class_name);
            res.setHeader('Content-Type', 'application/zip');
            res.setHeader('Content-Disposition', 'attachment; filename=' + reportName + '.zip');
            res.status(200);
            res.send(data);
        }
    });

});

reportRouter.post('/deleteReport', (req, res) => {
    const { id ,created_at } = req.body;
    try{
        db.deleteData('zip_progress', `id = '${id}'`);
        fs.unlink(path.join(__dirname, `../../pdfZip/${created_at.slice(0, 10)}/${id}.zip`), err => {
            if (err) {
                console.log(err);
                console.log(`删除失败：${id}====>${created_at}`);
            }
        });
        res.json({
            status: 200,
            message: '操作成功'
        });
    } catch (e) {
        throw e;
    }
})

module.exports = reportRouter;
